import React from 'react';
import { Button, Col, Row } from 'antd';
import HYInput from '../HYInput/HYInput';
import { InputProps } from 'antd/es/input';
import HYButton from "../HYButton/HYButton";

export interface HYVerificationInputProps extends InputProps {
  onSendCode: () => void;
}
export interface HYVerificationInputState {
  time: number;
}

/**
 * 验证码输入组件
 */
class HYVerificationInput extends React.Component<
  HYVerificationInputProps,
  HYVerificationInputState
> {
  interval: any;

  constructor(props) {
    super(props);
    this.state = {
      time: 0
    };
  }

  sendCode() {
    this.setState({ time: 10 });
    this.props.onSendCode();
    this.interval = setInterval(() => {
      let newTime = this.state.time - 1;
      if (newTime === 0) {
        clearInterval(this.interval);
        this.setState({ time: newTime });
      }
      this.setState({ time: newTime });
    }, 1000);
  }

  render() {
    const { time } = this.state;

    return (
      <Row>
        <Col span={8}>
          <HYInput {...this.props} />
        </Col>
        <Col span={4} offset={1}>
          <HYButton onClick={this.sendCode.bind(this)} disabled={time > 0}>
            {time > 0 ? `重发(${time}秒)` : '发送验证码'}
          </HYButton>
        </Col>
      </Row>
    );
  }
}

export default HYVerificationInput;
